package view;

import java.util.HashMap;
import java.util.Observable;
import java.util.Observer;

//import com.vandorenmes.argusv6_5.R;




import model.snippet.Snippet;
import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.graphics.Path;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
import android.view.ViewGroup.LayoutParams;

public class ARLayer extends View implements Observer
{
	private static final String TAG = SnippetView.class.getSimpleName();
	
	private HashMap<String, SnippetView> arSnippets;

	public ARLayer(Context context) 
	{
		super(context);

		setLayoutParams(new LayoutParams(0,0));		
		setLayoutParams(new ViewGroup.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT));		
		setLayerType(View.LAYER_TYPE_HARDWARE, new Paint());		

		this.arSnippets = new HashMap<String,SnippetView>();
		
		setWillNotCacheDrawing(true);
		setWillNotDraw(false);
		invalidate();
	}

	/**
	 * Add a new snippet to the view.
	 * @param newSnippet The snippet to add.
	 */
	public void addSnippetView(Snippet newSnippet)
	{		
		SnippetView view = new SnippetView(newSnippet);	
		arSnippets.put(newSnippet.getId(), view);
		
		newSnippet.addObserver(this);
	}
	
	/**
	 * Gets fired when observable sends a notification.
	 * <p>Tells view to draw the snippet</p>
	 * @param observable The snippet updated.
	 * @param data <i>Unused</i>
	 */
	@Override
	public void update(Observable observable, Object data) 
	{
		Snippet _snippet = null;
		
		try {
			_snippet = (Snippet) observable;
		} catch (ClassCastException e) {
			Log.e(TAG, String.format("%s", e.toString()));
		}
		 
		if(_snippet == null)
			return;
		
		if(arSnippets.containsKey(_snippet.getId()))
		{
			arSnippets.get(_snippet.getId()).update(_snippet);
			
			setWillNotCacheDrawing(true);
			setWillNotDraw(false);
			invalidate();
		}
	}
	
	/*
	 * draw all the snippets that are in the area the camera is looking at.
	 */
	@Override
	protected void onDraw(Canvas canvas) 
	{
		super.onDraw(canvas);

		canvas.save();
		
		for (SnippetView snippetView : arSnippets.values()) 
		{
			
			if(snippetView.isInArea())
			{
				Path _path = snippetView.getDrawableSnippetPath();
				Paint _paint = snippetView.getSnippetPaint();
				
				canvas.drawPath(_path, _paint);
			}
			
		}
		
		canvas.restore();
	}

	
	
}
